package net.xconcepts.stockdata.model.models;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import net.xconcepts.stockdata.model.Portfolio;
import net.xconcepts.stockdata.model.Prioritizer;
import net.xconcepts.stockdata.model.Trader;
import net.xconcepts.stockdata.model.TraderAction;
import net.xconcepts.stockdata.model.analysis.NumericRule;
import net.xconcepts.stockdata.model.analysis.SymbolFilter;
import net.xconcepts.stockdata.model.analysis.SymbolRule;
import net.xconcepts.stockdata.model.analysis.indicator.MACloseIndicator;
import net.xconcepts.stockdata.model.analysis.indicator.MovingAverageIndicator;
import net.xconcepts.stockdata.model.analysis.indicator.TrendIndicator;
import net.xconcepts.stockdata.model.analysis.symbol.Symbol;
import net.xconcepts.stockdata.model.analysis.symbol.SymbolFactory;
import net.xconcepts.stockdata.model.tick.SymbolTick;
import net.xconcepts.stockdata.model.tick.Tick;
import net.xconcepts.stockdata.model.tick.TickDataField;

public class AAPLModel extends Model {

	@Override
	protected Trader getTrader() {
		Portfolio portfolio = new Portfolio(10000);
		
		//Create AAPL Filter
		Symbol AAPL = SymbolFactory.getSymbol("AAPL");
		SymbolRule AAPLRule = new SymbolRule(AAPL);
		SymbolFilter AAPLFilter = new SymbolFilter(AAPLRule);
		
		MACloseIndicator maCloseIndicator = new MACloseIndicator(10);
		TrendIndicator buyTIndicator = new TrendIndicator(maCloseIndicator, 10);
		NumericRule buyRule = new NumericRule(buyTIndicator, 0, false);
		
		//Create Sell Rules		
		TrendIndicator tIndicator = new TrendIndicator(maIndicator, 10);
		NumericRule sellRule = new NumericRule(tIndicator, 0, true);
		
		
		//Create Prioritizer
		Prioritizer prioritizer = new Prioritizer(portfolio) {
			
			@Override
			public List<TraderAction> processMarketTick(
					Map<Symbol, SymbolTick> buyTicks,
					Map<Symbol, SymbolTick> sellTicks) {
				
				List<TraderAction> actions = new LinkedList<TraderAction>();
				
				for(SymbolTick tick : buyTicks.values()) {					
					if(getPortfolio().getCash() > tick.getData(TickDataField.Close)) {
						int amount = 
								(int) (getPortfolio().getCash() / tick.getData(TickDataField.Close));
						
						actions.add(createBuyAction(tick.getSymbol(),
								amount, tick));
					}
				}
				
				return actions;
			}
		};
		
		//Create Trader
		Trader trader = new Trader(portfolio, AAPLFilter, prioritizer);
		
		return trader;
	}

}
